import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author liangzai
 * @Description:
 */
public class Number2 {
    //字母异位词分组
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<Integer>> map = new HashMap<>();
        String[] str2 = new String[strs.length];
        for (int i = 0; i < strs.length; i++) {
            str2[i] = strs[i];
            Integer[] arr = new Integer[str2[i].length()];
            for (int j = 0; j < str2[i].length(); j++) {
                arr[j] = Integer.valueOf(str2[i].charAt(j));
            }
            Arrays.sort(arr);
            String key1 = Arrays.toString(arr);
            if(map.containsKey(key1)){
                List<Integer> val = map.get(key1);
                val.add(i);
            }else {
                List<Integer> val = new ArrayList<>();
                val.add(i);
                map.put(key1,val);
            }
        }
        List<List<String>> ret = new ArrayList<>();
        for(String key : map.keySet()){
            List<Integer> val = map.get(key);
            List<String> str = new ArrayList<>();
            for (int i = 0; i < val.size(); i++) {
                str.add(strs[val.get(i)]);
            }
            ret.add(str);
        }
        return ret;
    }

    //完善写法
    public List<List<String>> groupAnagrams2(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for (String str : strs) {
            //***********************
            //字符数组可以排序
            //***********************
            char[] chs = str.toCharArray();
            Arrays.sort(chs);
            String temp = new String(chs);
            if(map.containsKey(temp)){
                map.get(temp).add(str);
            }else {
                List<String> res = new ArrayList<>();
                res.add(str);
                map.put(temp,res);
            }
        }
        List<List<String>> res = map.entrySet().stream().map(item -> item.getValue()).collect(Collectors.toList());
        return res;
    }

//    public static void main(String[] args) {
//        System.out.println(Integer.valueOf('a'));
//    }
}
